/**
 * Created by dev on 99/8/4.
 */
'use strict';
import React, {Component} from 'react';
import {
    Platform,
    PixelRatio,
    NetInfo,
    Text,
    View,
    ActivityIndicator,
    AppRegistry,
    NativeModules,
    Dimensions
} from 'react-native';

import DimenSions from 'Dimensions';
import Md52 from './md52';

const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

module.exports = {
    /*最小线宽*/
    pixel: 1 / PixelRatio.get(),

    /*屏幕大小*/
    size: {
        width: DimenSions.get('window').width,
        height: DimenSions.get('window').height,
    },
    /*
     判断是IOS还是android系统
     */
    isIos() {
        if (Platform.OS === 'android') {
            return false;
        } else {
            return true;
        }


    },

    //判断是否联网
    async isNet() {
        try {
            let isConnected = await NetInfo.isConnected.fetch();

            return isConnected;
        }
        catch (e) {
            LOG(e.message);
        }

    },


    //数据MD5加密
    md5Data(data) {
        //  let signKey2 = signKey == null ? md5Key : signKey;
        let signKey2 = this.getKey();
        let str = "";
        for (let i in data) {
            if (i.indexOf('image_file_') == -1) {
                str = str + i + (data[i]);
            }
            LOG('str===' + str)
        }
        let str2 = signKey2 + str;
        return Md52.md5(str2);
    },

    getKey() {
        let key = Md52.md5(store_id * 2 + 1 + '');
        let md5_key = Md52.md5(key + 'qsy')
        LOG('md5_key===' + md5_key)
        return md5_key
    },
    /*
     对从服务器取得的数据进行加密比较
     */
    requestDataMd5(stringValue, signKey) {
        let signKey2 = signKey == null ? md5Key : signKey;
        let requestValue = JSON.parse(stringValue);
        let requestInfo = requestValue['resulet'];
        let requestsign = requestValue['sign'];
        // LOG('服务器返回的加密字符串=='+requestsign);
        let str2 = signKey2 + requestInfo;
        let md5value = Md52.md5(str2);
        LOG('md5value==' + md5value);
        LOG('requestsign==' + requestsign);
        if (md5value === requestsign) {

            return true;
        }
        return false;


    },


    /*
     obj的数据格式为
     let addData = {
     'Authorization': Authorization,
     'Mobile_key': Mobile_key,
     'consignee': adderusername,
     'region_id': final_region_id,
     'region_name': final_region_name,
     'address': xiangxidizhi,
     'zipcode': '510000',
     'phone_tel': '',
     };
     */
    toQueryString(obj) {
        return obj ? Object.keys(obj).map(function (key) {
            var val = obj[key];
            if (Array.isArray(val)) {
                return val.map(function (val2) {
                    return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
                }).join('&');
            }
            return encodeURIComponent(key) + '=' + encodeURIComponent(val);
        }).join('&') : '';
    },
    /*
     get请求数据的封装.
     datas的格式为 数组 let data['name']=name;
     */
    async get(url, datas, successcallback, errorcallback) {
        try {
            let isNet = await this.isNet();
            // let isNet = true;
            LOG('isNet========' + isNet)
            //if (isNet) {
            datas['t'] = Date.parse(new Date());
            let md5sign = this.md5Data(datas);
            let requestData = this.toQueryString(datas);
            url = url + '&' + requestData + '&sign=' + md5sign;
            LOG('GET请求接口======' + url);
            fetch(url).then((response) => response.text())
                .then((responseText) => {
                    let rrs = JSON.parse(responseText);
                    let data = JSON.parse(rrs.resulet)
                    successcallback(data);

                })
                .catch((error) => {
                    errorcallback(error);
                });
        } catch (e) {

        }


    },
    async post(url, data, successcallback, errorcallback) {
        LOG(url);
        try {
            let isNet = await this.isNet();
            //let isNet = true;
            //if (isNet) {
            data['t'] = Date.parse(new Date());
            let md5sign = this.md5Data(data);
            data['sign'] = md5sign
            let formData = new FormData();
            for (let keyName in data) {
                formData.append(keyName, data[keyName]);
            }
            let options = {
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                body: formData,
            };
            LOG('post请求的数据============' + JSON.stringify(options));

            fetch(url, options).then((response) => response.text())
                .then((responseText) => {
                    LOG('response====' + responseText)

                    let rrs = JSON.parse(responseText);
                    let data = JSON.parse(rrs['resulet']);

                    successcallback(JSON.parse(rrs['resulet']));


                })
                .catch(function (err) {

                    errorcallback(err)
                }).done();

        } catch (e) {

        }


    },


    post2(url, formData, successcallback, errorcallback) {
        LOG(url)
        let that = this;
        formData.append('store_id', 285551)
        NetInfo.isConnected.fetch().done((isConnected) => {
            let isIos = that.isIos();
            if (isIos) {
                isConnected = !isConnected;
            }
            if (isConnected) {
                let options = {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                    body: formData,
                };
                LOG('post请求的数据============' + JSON.stringify(options));
                fetch(url, options).then((response) => response.text())
                    .then((responseText) => {
                        LOG("POST 2 response===" + responseText);

                        let requestString = that.requestDataMd5(responseText, md5Key);

                        if (requestString == true) {
                            let rrs = JSON.parse(responseText);

                            successcallback(JSON.parse(rrs['resulet']));
                        } else {
                            errorcallback(-999)
                        }


                    })
                    .catch(function (err) {
                        LOG('post 请求错误==' + err);
                        errorcallback(err)
                    }).done();
            } else {
                errorcallback(-1);
            }
        });

    },
    /*
     去除字符串中的空格.如果要出去所有的空格,
     */
    stringTrim(str)
    {
        let result;
        result = str.replace(/(^\s+)|(\s+$)/g, "");

        return result;
    },
    /*
     当无法取得用户的唯一标示的时候调用此方法,返回一个虚拟的唯一标示
     唯一标示 3002C0B4-E33F-45F1-A61A-F87C04D9081C
     */
    getFictitiousDeviceId() {
        let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
        let maxPos = chars.length;
        let rs = "";
        let pwd = '';
        for (let i = 0; i < 8; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        rs = rs + pwd;

        for (let x = 0; x < 3; x++) {
            pwd = '';
            for (let i = 0; i < 4; i++) {
                pwd += chars.charAt(Math.floor(Math.random() * maxPos));

            }
            rs = rs + "-" + pwd;
        }
        pwd = '';
        for (let i = 0; i < 12; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        rs = rs + "-" + pwd;
        return rs;

    },
    /*
     获取指定strlength长度的随机字符串,tolower为大小的判断,1为大写,2为小写
     */
    getRandString(strlength, tolower) {
        let chars = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789abcdefghijkmnpqrstyvwxyz';

        let maxPos = chars.length;

        let pwd = '';
        for (let i = 0; i < strlength; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        if (tolower == 0) {
            return pwd;
        } else if (tolower == 1) {
            return pwd.toUpperCase()
        } else {
            return pwd.toLowerCase()
        }
    },
    emailRegular(email) {
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (filter.test(email)) {
            return true;
        }
        else {

            return false;
        }
    },

    loading() {

        return (<View style={{flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row'}}>
                <ActivityIndicator color="#999" style={{width: 20, height: 20,}}/>
                <Text style={{fontSize: 16, color: '#999'}}>加载中...</Text>
            </View>
        )


    },
    async openQQ(qq) {
        if (this.isIos()) {
            try {
                await this.props.navigator.push(
                    {
                        component: QQ,
                        passProps: {
                            uri: "mqq://im/chat?chat_type=crm&uin=" + qq + "&version=1&src_type=web",
                            title: "联系客服"
                        }
                    }
                );
                this.props.navigator.pop();
            } catch (err) {
                LOG('eerr===' + err)
            }

        } else {
            NativeModules.CommonModule.openUrl("mqqwpa://im/chat?chat_type=wpa&uin=" + qq);
        }
    },
    opening() {
        MyToast.show('等待开发')
    },
};